/**
* @describe 节点处理工具类
* @author 游金宇(KM)
* @date 2024-09-12 11:40:45
*/

import { cat } from "@shimotsuki/core";
import { Component, ImageAsset, Layers, Node, Sprite, SpriteAtlas, SpriteFrame, error, isValid } from "cc";


/**
 * 设置节点变灰
 * @param node 节点
 * @param gray 灰色|正常
 * @param recuesion 自身 | 所有元素
 */
export const setNodeGray = (node: Node | Component, gray: boolean = true, recuesion: boolean = true) => {
    const nonce = node instanceof Component ? node.node : node
    if (recuesion) {
        nonce.getComponentsInChildren(Sprite).forEach(item => {
            setSpriteGray(item, gray)
        })
    } else {
        nonce.getComponents(Sprite).forEach(item => {
            setSpriteGray(item, gray)
        })
    }
}


export const setSpriteGray = (sp: Sprite, gray: boolean) => {
    sp.grayscale = gray
}

/**
 * 从图集中获取精灵图
 * @param imageAtlas 图集
 * @param spriteFrameName 精灵图名称
 * @returns 
 */
export const getSpriteFrameFromimageAtlas = (imageAtlas: SpriteAtlas, spriteFrameName: string): Promise<SpriteFrame> => {
    return new Promise<SpriteFrame>((resolve, reject) => {
        const nonce = imageAtlas.getSpriteFrame(spriteFrameName)
        if (nonce) {
            resolve(nonce)
        } else {
            cat.res.loadRemote(spriteFrameName, (err: Error, imageAsset: ImageAsset) => {
                if (err || !isValid(imageAtlas)) {
                    reject(err)
                } else {
                    const nonce = SpriteFrame.createWithImage(imageAsset)
                    imageAtlas.spriteFrames[spriteFrameName] = nonce
                    resolve(nonce)
                }
            })
        }

    })

}

/**设置节点及子节点的层级 */
export const setNodeAndChildrenLayer = (node: Node, layer: string | Layers.Enum) => {
    node.layer = (typeof layer === 'string' ? 2 ** Layers.nameToLayer(layer) : layer)
    node?.children.forEach(item => {
        setNodeAndChildrenLayer(item, layer)
    })
}

/**
 * 设置精灵到Sprite
 * @param url 精灵url
 * @param s 渲染精灵组件
 * @param packable 设置精灵是否允许参与自动合图
 * @returns 
 */
export const setSpriteFrameToSprite = (url: string, s: Sprite, packable = true) => {
    cat.res.loadRemote(url, (err: Error, imageAsset: ImageAsset) => {
        if (err) return error(err)
        if (isValid(s)) {
            const spriteFrame = SpriteFrame.createWithImage(imageAsset)
            spriteFrame.packable = packable
            s.spriteFrame = spriteFrame
        }
    })

}